# coding: utf-8

import json

from flask import jsonify, request, render_template, flash

from app.compute.compute_func import Quotation
from app.compute.compute_process import QuotationProcess
from app.compute.forms import CalPriceForm
from app.compute.options import ProductOptions
from app.exceptions import NotProductError, InputError
from app.products.constant import SceneType, ColorType, InstallWay, TypeToName
from . import compute_bp


@compute_bp.route('/ajax/quotation/compute')
def ajax_quotation_compute():
    """
    报价查询
    :return:
    """
    try:

        result = QuotationProcess(request.args).quotation_models()
        return jsonify(dict(
            status=0,
            data=str(result)
        ))
    except NotProductError as e:
        return jsonify(
            dict(status=1, message=str(e))
        )


@compute_bp.route('/calculate/price', methods=['GET', 'POST'])
def calculate_price():
    """
    查询报价/报价结果展示
    :return:
    """
    form = CalPriceForm()
    try:
        if form.validate_on_submit():
            prices = Quotation(form).quotation_models()
            total = sum(
                [each.get('total', 0) if each else 0 for each in prices])

            return render_template(
                "/price/price_list.html",
                prices=prices,
                total=total,
                form=form,
                scene_type=SceneType.mapping.get(form.scene_type.data),
                color=ColorType.mapping.get(form.color.data),
                spacing='P{}'.format(form.spacing.data),
                wide_high='{}*{}m'.format(form.wide.data, form.high.data),
                install_way=InstallWay.mapping.get(form.install_way.data)
            )
    except NotProductError as e:
        flash(str(e))
    return render_template(
        "/price/input_form.html",
        form=form,
    )


@compute_bp.route('/calculate/prices', methods=['GET', 'POST'])
def calculate_prices():
    form = CalPriceForm()
    try:
        if form.validate_on_submit():
            prices = QuotationProcess(form).quotation_models()
            prices = [price for price in prices if float(price['quantity'])]
            total = sum(
                [float(each.get('total', 0)) if each else 0 for each in prices
                 if each.get('necessary')])

            return render_template(
                "/price/prices_list.html",
                products=json.dumps(dict()),
                prices=prices,
                total=total,
                form=form,
                scene_type=SceneType.mapping.get(form.scene_type.data),
                color=ColorType.mapping.get(form.color.data),
                spacing='P{}'.format(form.spacing.data),
                wide_high='{}*{}m'.format(form.wide.data, form.high.data),
                install_way=InstallWay.mapping.get(form.install_way.data)
            )
    except (NotProductError, InputError) as e:
        flash(str(e))
    return render_template(
        "/price/prices_input_form.html",
        form=form,
    )


@compute_bp.route('/ajax/option/products')
def ajax_option_products():
    """
    产品下拉框
    :return:
    """
    try:

        options = ProductOptions(request.args).option_values()
        type_id = request.args.get('type_id', type=int)
        product_id = request.args.get('product_id', type=int)
        return render_template(
            "/price/partial/product_option_modal.html",
            options=options,
            type_id=type_id,
            product_id=product_id,
            type_name=TypeToName.mapping.get(type_id)
        )
    except NotProductError as e:
        return jsonify(
            dict(status=1, message=str(e))
        )
